'use client';

import { useState, useRef, useEffect } from 'react';

function SingleImageViewer({ imageUrl, imageName, detections = [], title }) {
  const canvasRef = useRef(null);
  const [scale, setScale] = useState(1);
  const [offset, setOffset] = useState({ x: 0, y: 0 });
  const [isDragging, setIsDragging] = useState(false);
  const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
  const [image, setImage] = useState(null);

  // 固定窗口尺寸（像素单位）
  const WINDOW_WIDTH = 500;  // 固定宽度
  const WINDOW_HEIGHT = 500; // 固定高度

  // 加载图像
  useEffect(() => {
    if (imageUrl) {
      const img = new Image();
      img.onload = () => {
        setImage(img);
        setScale(1);
        setOffset({ x: 0, y: 0 });
      };
      img.src = imageUrl;
    }
  }, [imageUrl]);

  // 绘制图像（固定 Canvas 尺寸 + 自适应图像）
  const drawImage = () => {
    const canvas = canvasRef.current;
    if (!canvas || !image) return;

    const ctx = canvas.getContext('2d');

    // 固定 Canvas 尺寸
    canvas.width = WINDOW_WIDTH;
    canvas.height = WINDOW_HEIGHT;
    ctx.clearRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

    // 计算图像在窗口内的最大缩放比例（保持比例）
    const canvasRatio = WINDOW_WIDTH / WINDOW_HEIGHT;
    const imageRatio = image.width / image.height;
    let scaleRatio = 1;

    if (imageRatio > canvasRatio) {
      // 图像更宽：按窗口高度缩放
      scaleRatio = WINDOW_HEIGHT / image.height;
    } else {
      // 图像更高：按窗口宽度缩放
      scaleRatio = WINDOW_WIDTH / image.width;
    }

    // 应用用户缩放（限制范围）
    const displayScale = Math.max(0.1, Math.min(5, scale * scaleRatio));
    const scaledWidth = image.width * displayScale;
    const scaledHeight = image.height * displayScale;

    // 居中显示
    const x = (WINDOW_WIDTH - scaledWidth) / 2 + offset.x;
    const y = (WINDOW_HEIGHT - scaledHeight) / 2 + offset.y;

    ctx.drawImage(image, x, y, scaledWidth, scaledHeight);

    // 绘制检测结果
    if (detections && detections.length > 0) {
      ctx.strokeStyle = '#ff0000';
      ctx.lineWidth = 2;
      ctx.fillStyle = 'rgba(255, 0, 0, 0.1)';

      detections.forEach(detection => {
        const detectionX = x + detection.x * scale;
        const detectionY = y + detection.y * scale;
        const detectionWidth = detection.width * scale;
        const detectionHeight = detection.height * scale;

        ctx.strokeRect(detectionX, detectionY, detectionWidth, detectionHeight);
        ctx.fillRect(detectionX, detectionY, detectionWidth, detectionHeight);

        ctx.fillStyle = '#ffffff';
        ctx.fillRect(detectionX, detectionY - 20, 60, 20);
        ctx.fillStyle = '#000000';
        ctx.font = '12px Arial';
        ctx.fillText(`${(detection.confidence * 100).toFixed(1)}%`, detectionX + 5, detectionY - 5);
      });
    }
  };

  // 重绘画布
  useEffect(() => {
    drawImage();
  }, [image, scale, offset, detections]);

  // 交互操作（坐标基于固定窗口尺寸）
  const handleMouseDown = (e) => {
    const rect = canvasRef.current.getBoundingClientRect();
    setIsDragging(true);
    setDragStart({
      x: e.clientX - rect.left - offset.x,
      y: e.clientY - rect.top - offset.y,
    });
  };

  const handleMouseMove = (e) => {
    if (isDragging) {
      const rect = canvasRef.current.getBoundingClientRect();
      setOffset({
        x: e.clientX - rect.left - dragStart.x,
        y: e.clientY - rect.top - dragStart.y,
      });
    }
  };

  const handleMouseUp = () => {
    setIsDragging(false);
  };

  const handleWheel = (e) => {
    e.preventDefault();
    const delta = e.deltaY > 0 ? 0.9 : 1.1;
    setScale(Math.max(0.1, Math.min(5, scale * delta)));
  };

  // 重置视图（自适应窗口）
  const resetView = () => {
    if (!image) return;
    const canvasRatio = WINDOW_WIDTH / WINDOW_HEIGHT;
    const imageRatio = image.width / image.height;
    let resetScale = 1;

    if (imageRatio > canvasRatio) {
      resetScale = WINDOW_HEIGHT / image.height;
    } else {
      resetScale = WINDOW_WIDTH / image.width;
    }

    setScale(resetScale);
    setOffset({ x: 0, y: 0 });
  };

  // 在组件顶部的状态声明中保留这一行
  const [inputValue, setInputValue] = useState('');

  return (
    <div className="flex-1">
      <div className="flex justify-between items-center mb-2">
        <h4 className="text-sm font-medium text-gray-700">{title}</h4>
        <div className="flex space-x-2 items-center">
          <button
            onClick={() => setScale(Math.max(0.1, scale - 0.1))}
            className="px-2 py-1 text-xs bg-gray-200 hover:bg-gray-300 rounded"
          >
            缩小
          </button>

          {/* 替换原有的显示文本为可输入的数值控制 */}
          <div className="flex items-center border rounded overflow-hidden h-[22px]">
            <input
              type="text"
              value={inputValue === '' ? Math.round(scale * 100) : inputValue}
              onChange={(e) => {
                // 允许空字符串、数字字符和退格键
                const newValue = e.target.value;
                setInputValue(newValue);

                // 只有当输入是有效的完整数字时才更新缩放
                if (/^\d+$/.test(newValue)) {
                  const value = parseInt(newValue, 10);
                  if (value >= 1 && value <= 500) {
                    setScale(value / 100);
                  }
                }
              }}
              onKeyDown={(e) => {
                // 按回车键应用更改并清除临时输入
                if (e.key === 'Enter') {
                  e.target.blur(); // 触发 onBlur 事件
                }
              }}
              onFocus={(e) => {
                // 聚焦时选择全部文本并存储当前值
                e.target.select();
              }}
              onBlur={() => {
                // 失去焦点时应用有效的值
                if (inputValue === '' || isNaN(parseInt(inputValue))) {
                  // 输入为空或非数字，保持当前缩放
                  setInputValue('');
                } else {
                  // 输入是数字，确保在允许范围内
                  const value = parseInt(inputValue, 10);
                  if (value < 1) {
                    setScale(0.01);
                  } else if (value > 500) {
                    setScale(5);
                  } else {
                    setScale(value / 100);
                  }
                  setInputValue(''); // 重置输入值
                }
              }}
              className="w-14 text-xs text-center py-0 h-full outline-none"
              style={{
                appearance: 'textfield',
                MozAppearance: 'textfield',
                WebkitAppearance: 'none'
              }}
            />
            <div className="flex flex-col border-l h-full">
              <button
                onClick={() => setScale(Math.min(5, scale + 0.01))}
                className="px-1 text-xs bg-gray-100 hover:bg-gray-200 border-b h-[11px] flex items-center justify-center"
              >
                ▲
              </button>
              <button
                onClick={() => setScale(Math.max(0.1, scale - 0.01))}
                className="px-1 text-xs bg-gray-100 hover:bg-gray-200 h-[11px] flex items-center justify-center"
              >
                ▼
              </button>
            </div>
            <span className="px-1 text-xs bg-gray-50 h-full flex items-center">%</span>
          </div>

          <button
            onClick={() => setScale(Math.min(5, scale + 0.1))}
            className="px-2 py-1 text-xs bg-gray-200 hover:bg-gray-300 rounded"
          >
            放大
          </button>
          <button
            onClick={resetView}
            className="px-2 py-1 text-xs bg-blue-500 text-white hover:bg-blue-600 rounded"
          >
            重置
          </button>
        </div>
      </div>

      {/* 固定窗口大小 */}
      <div className="border border-gray-300 rounded-lg overflow-hidden bg-gray-50 w-full">
        {image ? (
          <canvas
            ref={canvasRef}
            width={WINDOW_WIDTH}
            height={WINDOW_HEIGHT}
            className="block cursor-move w-full"
            style={{ height: `${WINDOW_HEIGHT}px` }} // 固定高度
            onMouseDown={handleMouseDown}
            onMouseMove={handleMouseMove}
            onMouseUp={handleMouseUp}
            onMouseLeave={handleMouseUp}
            onWheel={handleWheel}
          />
        ) : (
          <div className="w-full h-[500px] flex items-center justify-center text-gray-500">
            {imageName ? `加载中: ${imageName}` : '请选择图像'}
          </div>
        )}
      </div>

      <div className="mt-2 text-xs text-gray-500 text-center">
        使用鼠标拖拽平移，滚轮缩放
      </div>
    </div>
  );
}

// 父组件
export default function ImageViewer2D({ imageUrl, imageName, detections = [] }) {
  return (
    <div className="space-y-4">
      <h3 className="text-lg font-semibold text-gray-900">2D图像查看器</h3>

      <div className="flex space-x-4">
        <SingleImageViewer
          imageUrl={imageUrl}
          imageName={imageName}
          detections={[]}
          title="原始图像"
        />
        <SingleImageViewer
          imageUrl={imageUrl}
          imageName={imageName}
          detections={detections}
          title="处理结果"
        />
      </div>

      <div className="text-sm text-gray-600 bg-blue-50 p-3 rounded-lg">
        <strong>说明：</strong>左侧显示原始图像，右侧显示处理结果。两个窗口都支持独立的缩放、平移操作。
      </div>
    </div>
  );
}
